<template>
    <div class="card">
        <div class="big-box">
          <el-card class="card-style">
            <div class="form-style">
              <h2 style="text-align: center;">题库中知识点数量统计表</h2>
              <div style="display: flex;  background-color: #fff;">
                <el-table :data="leftTableData" border style="width: 50%; height: 85%;">
                  <el-table-column prop="question_type" label="知识点" class="name-column" align="center"></el-table-column>
                  <el-table-column prop="total_num" label="数量" align="center"></el-table-column>
                </el-table>
                <el-table :data="rightTableData" border style="width: 50%; height: 85%;">
                  <el-table-column prop="question_type" label="知识点" class="name-column" align="center"></el-table-column>
                  <el-table-column prop="total_num" label="数量" align="center"></el-table-column>
                </el-table>
              </div>
            </div>
          </el-card>
          <el-card  class="card-style">
            <div id="typeKnowledgeChart" ref="typeKnowledgeChart" class="histogram" style="height: 900px;"></div>
          </el-card>
          <el-card  class="card-style">
            <div ref="difficultyKnowledgeChart" class="histogram" style="width: 100%; height: 400px;"></div>
          </el-card>
          <el-card  class="card-style">
            <div ref="chartDom" class="histogram" style="height: 500px;width: 90%;"></div>
          </el-card>
          <el-card  class="card-style">
            <div ref="lineChart" class="histogram"></div>
          </el-card>
    
          <el-card class="card-style">
            <div ref="echartsContainer" class="histogram"></div>
          </el-card>
        </div>
    </div><!-- <basicColumnChart></basicColumnChart> -->
  </template>
  
<script setup>
import { deleteTitleData, getTotalTitle, getTotalTitleNum,getDifficultyNum,getTagNum,getYearNum,getTypeKnowledgeNum,getQuestionTypesDifficultyNum } from '@/api/questionBank.js';
import { useClassStore } from '@/stores/index.js'
import * as echarts from 'echarts';
import { ref,reactive, onMounted, nextTick } from 'vue';
import basicColumnChart from '@/components/basicColumnChart.vue'

const chartDom = ref(null);
const echartsContainer = ref(null);
const lineChart = ref(null)
//题型知识点统计表
const typeKnowledgeChart = ref(null)
//难度知识点表
const difficultyKnowledgeChart = ref(null)
const subInfo = reactive({
  syllabusId:0,
  subId:0,
  class_name:'',
  grade_name:'',
  subject:'',
})
//一进入页面，则把该班级的大纲id给页面
const classMessage = useClassStore()
// syllabusId.value = classMessage.classInfo.id
subInfo.syllabusId = classMessage.classInfo.user_and_acs_id//大纲id
subInfo.subId = classMessage.classInfo.subId
subInfo.class_name = classMessage.classInfo.class_name
subInfo.grade_name = classMessage.classInfo.grade_name
subInfo.subject = classMessage.classInfo.subject

//获取知识点表格数据
const tableData = reactive([])
const leftTableData = reactive([]);
const rightTableData = reactive([]);
const getTableData = async () =>{
  const res = await getTagNum(subInfo.subId)
  res.data.data.forEach((value,index) =>{
    tableData.push(value)
  })
  const halfIndex = Math.ceil(tableData.length / 2);
  leftTableData.push(...tableData.slice(0, halfIndex));
  rightTableData.push(...tableData.slice(halfIndex));
}
//获取知识点表格数据
getTableData()

//获取年份上传题目数据
const lineData = reactive([])
const getLineData = async () =>{
  const res = await getYearNum(subInfo.subId)
  console.log(res,'gadghaerg');
  res.data.data.forEach((value,index) =>{
    lineData.push(value)
  })
  //折线图
  const myLine  = echarts.init(lineChart.value);
  const lineOption = {
    title: {
      text: '每月添加题目统计',
      // subtext: 'Fake Data',
      left: 'center',
      textStyle: {
              fontSize: 24, // 设置标题字体大小为24px
          }
    },
    xAxis: {
      type: 'category',
      // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
      data:  lineData.map((item) =>item.created_at)
    },
    yAxis: {
      type: 'value'
    },
    tooltip: {
          trigger: 'axis', // 设置触发提示框的方式为坐标轴触发
          formatter: params => `${params[0].name}: ${params[0].value} 题` // 设置提示框的内容格式，显示数量
        },
    series: [
      {
        data: lineData.map((item) =>item.total_num),
        type: 'line'
      }
    ]
  };
  myLine.setOption(lineOption);
}
//获取年份上传题目数据
getLineData()

//获取题目数量
const getQuestionTypesNum = async () =>{
  const resNum = await getTotalTitleNum(subInfo.subId );
  const data = reactive([])
  resNum.data.data.forEach((value,index)=> {
    data.push(value)
  });
  if (echartsContainer.value) {
  // 初始化 Echarts 实例
  const myChart = echarts.init(echartsContainer.value);
    
  // 准备数据
  // const data = [
  //   { name: '单项选择题', value: resNum.data.单项选择题},
  //   { name: '多项选择题', value: resNum.data.多项选择题 },
  //   { name: '填空题', value: resNum.data.填空题 },
  //   { name: '判断题', value: resNum.data.判断题 },
  //   { name: '组合题', value: resNum.data.组合题 }
  // ];
    
      // 绘制柱形统计图
  myChart.setOption({
      title: {
          text: '题目类型统计',
          x: 'center',
          textStyle: {
              fontSize: 24, // 设置标题字体大小为24px
          }
      },
      tooltip: {
          trigger: "axis", //垂直线
          axisPointer: {
          type: 'cross' //十字线
          }
      },
      xAxis: {
          type: 'category',
          data: data.map(item => item.question_type),
          axisLabel: {
          // inside: true,
          // color: '#fff'
          },
          axisTick: {
          show: false
          },
          axisLine: {
          show: false
          },
          z: 10
      },
      yAxis: {
          type: 'value',
          axisLine: {
          show: false
          },
          axisTick: {
          show: false
          },
          axisLabel: {
          color: '#999'
          }
      },
      series: [{
          data: data.map(item => item.total_num),
          type: 'bar',
          showBackground: true,
          // itemStyle: {
          // color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          //     { offset: 0, color: '#83bff6' },
          //     { offset: 0.5, color: '#188df0' },
          //     { offset: 1, color: '#188df0' }
          // ])
          // },
          // emphasis: {
          // itemStyle: {
          //     color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          //     { offset: 0, color: '#2378f7' },
          //     { offset: 0.7, color: '#2378f7' },
          //     { offset: 1, color: '#83bff6' }
          //     ])
          // }
          // },
      }]
      });
  }
}
//获取题目数量
getQuestionTypesNum()

//获取题目难度数量
const difficultyNumPie = async () =>{
  const res = await getDifficultyNum(subInfo.subId )
  // 准备数据
  const difficultyData = reactive([])
  res.data.data.forEach((value,index) =>{
    difficultyData.push(value)
    // difficultyData[index].name = value.difficulty
    // difficultyData[index].value = value.total_num
  })
  const myPie  = echarts.init(chartDom.value);
  const option = {
    title: {
      text: '题目难度统计',
      // subtext: 'Fake Data',
      left: 'center',
      textStyle: {
              fontSize: 24, // 设置标题字体大小为24px
          }
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'right', // 将 left 改为 right
      top: 50, // 可以根据需要调整上边距
      fontSize: 25
    },
    grid: {
          top: 0, // 调整图表位置
          bottom: 0,
          left: 0,
          right: 0,
          containLabel: true
      },
    series: [
      {
        // name: 'Access From',
        type: 'pie',
        radius: '60%',
        data: difficultyData.map(item => ({
                  value: item.total_num,
                  name: item.difficulty
              })),
        label: {
        fontSize: 16, // 调整字体大小
        fontWeight: 'bold', // 可以添加其他样式
        formatter: '{b}: {c}题 ({d}%)', // 可以设置标签显示的内容，{b} 表示名称，{c} 表示值，{d} 表示百分比
        left:'50px',
        },
        labelLine: {
            length: 40, // 连线长度
            length2: 50, // 连线第二段长度
            smooth: true, // 平滑曲线
            lineStyle: {
                // 连线样式
                width: 2,
                color: 'rgba(0,0,0,0.3)'
            }
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  myPie.setOption(option);
}
//题目难度统计
difficultyNumPie()

//题型知识点统计
const TypeKnowledgeNum = async () =>{

}
TypeKnowledgeNum()

onMounted(async () => {
  // 初始化 ECharts 实例
  const chartDom = document.getElementById('typeKnowledgeChart');
  const myChart = echarts.init(chartDom);

  // 显示加载动画
  myChart.showLoading();

  const typeKnowledgeData = reactive([])
  const resType = await getTypeKnowledgeNum(subInfo.subId)
  resType.data.data.forEach((value,index) =>{
    typeKnowledgeData.push(value)
  })
  // 静态示例数据
  // const data = {
  //   name: '知识体系',
  //   children: [
  //     {
  //       name: '单项选择题',
  //       children: [
  //         { name: '基础知识' },
  //         { name: '数组' },
  //       ]
  //     },

  //   ]
  // };
  const data = reactive({
    name:`${subInfo.subject}`,
    children:[
      {
        name:'',
        children:[],
      }
    ]
  })
  typeKnowledgeData.forEach((value, index) => {

  // 确保 data.children 数组足够长
  if (!data.children[index]) {
    data.children[index] = {
      name: '',
      children: [],
    };
  }

  value.labels.forEach((value1,index1) =>{
    const newItem = {
      name: value1,
    };
    if(newItem.name !== '')
    data.children[index].children.push(newItem);
  })
  data.children[index].name = value.question_type;
});

  // 隐藏加载动画
  myChart.hideLoading();

  // 对每个偶数索引的子节点进行折叠操作
  data.children.forEach((datum, index) => {
    if (index % 2 === 0) {
      datum.collapsed = true;
    }
  });

  // 设置图表配置项
  myChart.setOption({
    title: {
      text: '题型知识点统计',
      // subtext: 'Fake Data',
      left: 'center',
      textStyle: {
              fontSize: 24, // 设置标题字体大小为24px
          }
    },
    tooltip: {
      trigger: 'item',
      triggerOn: 'mousemove'
    },
    series: [
      {
        type: 'tree',
        data: [data],
        top: '1%',
        left: '7%',
        bottom: '1%',
        right: '20%',
        symbolSize: 7,
        label: {
          position: 'left',
          verticalAlign: 'middle',
          align: 'right',
          fontSize: 9
        },
        leaves: {
          label: {
            position: 'right',
            verticalAlign: 'middle',
            align: 'left'
          }
        },
        emphasis: {
          focus: 'descendant'
        },
        expandAndCollapse: true,
        animationDuration: 550,
        animationDurationUpdate: 750
      }
    ]
  });

// const resDiff = await getQuestionTypesDifficultyNum(1)
// console.log(resDiff.data.data,'1111112');
// // 初始化 ECharts 实例
// const myChart1 = echarts.init(difficultyKnowledgeChart.value);

// // 设置图表配置项
// const option = {
//   legend: {
//     top: 'bottom'
//   },
//   toolbox: {
//     show: true,
//     feature: {
//       mark: { show: true },
//       dataView: { show: true, readOnly: false },
//       restore: { show: true },
//       saveAsImage: { show: true }
//     }
//   },
//   series: [
//     {
//       name: 'Nightingale Chart',
//       type: 'pie',
//       radius: ['30%', '80%'],
//       center: ['50%', '50%'],
//       roseType: 'area',
//       itemStyle: {
//         borderRadius: 8
//       },
//       data: [
//         { value: 40, name: 'rose 1' },
//         { value: 38, name: 'rose 2' },
//         { value: 32, name: 'rose 3' },
//         { value: 30, name: 'rose 4' },
//         { value: 28, name: 'rose 5' },
//         { value: 26, name: 'rose 6' },
//         { value: 22, name: 'rose 7' },
//         { value: 18, name: 'rose 8' }
//       ]
//     }
//   ]
// };

// // 设置图表配置
// myChart1.setOption(option);
});



onMounted( async () => {
const data = reactive([])
const resDiff = await getQuestionTypesDifficultyNum(subInfo.subId)
console.log(resDiff.data.data,'1111112');
resDiff.data.data.forEach((value,index) =>{
  data.push(value)
})
console.log(data,'data');

// 收集所有可能的难度级别
const allDifficulties = Array.from(new Set(data.flatMap(item => item.labels.map(label => label.difficulty))));

// 构建 rawData
const rawData = data.map(item => {
  const counts = Array(allDifficulties.length).fill(0);
  item.labels.forEach(label => {
    const index = allDifficulties.indexOf(label.difficulty);
    counts[index] = label.count;
  });
  return counts;
});

// 计算 totalData
const totalData = [];
for (let i = 0; i < rawData[0].length; ++i) {
  let sum = 0;
  for (let j = 0; j < rawData.length; ++j) {
    sum += rawData[j][i];
  }
  totalData.push(sum);
}

// 配置 ECharts 选项
const grid = {
  left: 100,
  right: 100,
  top: 50,
  bottom: 50
};

const series = data.map((item, sid) => {
  return {
    name: item.question_type,
    type: 'bar',
    stack: 'total',
    barWidth: '60%',
    label: {
      show: true,
      formatter: (params) => Math.round(params.value * 1000) / 10 + '%',
    },
    data: rawData[sid].map((d, did) =>
      totalData[did] <= 0 ? 0 : d / totalData[did]
    ),
  };
});
// title: {
//       text: '题型知识点统计',
//       // subtext: 'Fake Data',
//       left: 'center',
//       textStyle: {
//               fontSize: 24, // 设置标题字体大小为24px
//           }
//     },

const option = {
  title: {
    text: '难度题型统计', // 设置顶部标题的文本内容
    left: 'center', // 居中对齐
    textStyle: {
      fontSize: 24, // 标题字体大小
      fontWeight: 'bold' // 标题字体粗细
    },
    top: '0%' // 顶部距离调整，可以根据需要进行修改
  },
  legend: {
    selectedMode: false,
    orient: 'vertical',
    right: 0
  },
  grid,
  yAxis: {
    type: 'value'
  },
  xAxis: {
    type: 'category',
    data: allDifficulties
  },
  series
};

// 初始化图表
// const chart = ref(null);
  const chartInstance = echarts.init(difficultyKnowledgeChart.value);
  chartInstance.setOption(option);
});





  </script>
  
<style scoped>
  .card {
    /* width: 900px; */
    /* width: 100%; */
    box-sizing: border-box;
    margin: 0 auto;
    padding: 20px;
    background-color: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, .1);
    transition: box-shadow .3s ease;
    justify-content:center;
    display:flex;
    width:100%;
    min-height:50vh;
    /* overflow-x:hidden; */
}

.big-box{
    /* display:flex; */
    width:100%;
    justify-content:space-between;
    margin: 0 auto;
    /* min-height:100%; */

}

.card-style{
  margin-top: 10px;
  /* background-color: #fcfafa; */
}

.form-style{
  margin-bottom: 30px;
}

.name-column {
  width: 50%;
}

.histogram{
    width:60%;
    height:400px;
    margin: 0 auto;
    margin-bottom: 20px;
}
</style>